"use client";
import { Card, Row, Col, Statistic, Table, Typography, Divider } from "antd";
import { UserOutlined, FileTextOutlined, ShoppingOutlined, EyeOutlined } from "@ant-design/icons";
import AdminLayout from "@/components/AdminLayout";
import { useEffect, useState } from "react";
import { adminAPI, Article, ArticleStats, Case, CaseStats, Product, ProductStats, adminUserAPI } from "@/lib/api";

const { Title, Text } = Typography;

export default function AdminDashboard() {
  const [articleStats, setArticleStats] = useState<ArticleStats | null>(null);
  const [caseStats, setCaseStats] = useState<CaseStats | null>(null);
  const [productStats, setProductStats] = useState<ProductStats | null>(null);
  const [userStats, setUserStats] = useState<{ total: number; active: number; inactive: number } | null>(null);
  const [recentArticles, setRecentArticles] = useState<Article[]>([]);
  const [recentCases, setRecentCases] = useState<Case[]>([]);
  const [recentProducts, setRecentProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        // 使用Promise.all并发请求
        const [statsRes, articlesRes, caseStatsRes, casesRes, productStatsRes, productsRes, usersRes] = await Promise.all([adminAPI.getArticleStats(), adminAPI.getArticles({ page: 1, limit: 5 }), adminAPI.getCaseStats(), adminAPI.getCases({ page: 1, limit: 5 }), adminAPI.getProductStats(), adminAPI.getProducts({ page: 1, pageSize: 5 }), adminUserAPI.getUsers()]);

        if (statsRes.success) {
          setArticleStats(statsRes.data);
        }

        if (articlesRes.success) {
          setRecentArticles(articlesRes.data.articles);
        }

        if (caseStatsRes.success) {
          setCaseStats(caseStatsRes.data);
        }

        if (casesRes.success) {
          setRecentCases(casesRes.data.cases);
        }

        if (productStatsRes.success) {
          setProductStats(productStatsRes.data);
        }

        if (productsRes.success) {
          setRecentProducts(productsRes.data.products);
        }

        if (usersRes.success) {
          const users = usersRes.data;
          const total = users.length;
          const active = users.filter(user => user.status).length;
          const inactive = users.filter(user => !user.status).length;
          setUserStats({ total, active, inactive });
        }

        // 如果任一请求失败，可以在这里添加统一的错误提示
        if (!statsRes.success || !articlesRes.success || !caseStatsRes.success || !casesRes.success || !productStatsRes.success || !productsRes.success || !usersRes.success) {
          console.error("部分数据加载失败:", { statsRes, articlesRes, caseStatsRes, casesRes, productStatsRes, productsRes, usersRes });
        }
      } catch (error) {
        // 由axios拦截器处理了401跳转，这里只处理其他错误
        console.error("加载仪表盘数据失败:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  const articleColumns = [
    {
      title: "文章标题",
      dataIndex: "title",
      key: "title",
      render: (text: string) => <Text strong>{text}</Text>,
    },
    {
      title: "作者",
      dataIndex: "author",
      key: "author",
    },
    {
      title: "浏览量",
      dataIndex: "views",
      key: "views",
      render: (views: number) => (
        <span>
          <EyeOutlined style={{ marginRight: 4 }} />
          {views?.toLocaleString?.() ?? views}
        </span>
      ),
    },
    {
      title: "更新人",
      dataIndex: "author",
      key: "author",
    },
    {
      title: "发布时间",
      dataIndex: "publishedAt",
      key: "publishedAt",
      render: (date: string) => (date ? date.slice(0, 10) : "-"),
    },
  ];

  const caseColumns = [
    {
      title: "攻略标题",
      dataIndex: "title",
      key: "title",
      render: (text: string) => <Text strong>{text}</Text>,
    },
    {
      title: "作者",
      dataIndex: "author",
      key: "author",
    },
    {
      title: "浏览量",
      dataIndex: "views",
      key: "views",
      render: (views: number) => (
        <span>
          <EyeOutlined style={{ marginRight: 4 }} />
          {views?.toLocaleString?.() ?? views}
        </span>
      ),
    },
    {
      title: "更新人",
      dataIndex: "author",
      key: "author",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (date: string) => (date ? date.slice(0, 10) : "-"),
    },
  ];

  const productColumns = [
    {
      title: "产品标题",
      dataIndex: "title",
      key: "title",
      render: (text: string) => <Text strong>{text}</Text>,
    },
    {
      title: "作者",
      dataIndex: "author",
      key: "author",
    },
    {
      title: "浏览量",
      dataIndex: "views",
      key: "views",
      render: (views: number) => (
        <span>
          <EyeOutlined style={{ marginRight: 4 }} />
          {views?.toLocaleString?.() ?? views}
        </span>
      ),
    },
    {
      title: "更新人",
      dataIndex: "author",
      key: "author",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (date: string) => (date ? date.slice(0, 10) : "-"),
    },
  ];

  return (
    <AdminLayout>
      <div style={{ background: "#fff", padding: 24, borderRadius: 8 }}>
        <Title level={2}>仪表盘</Title>
        <Divider />

        {/* 统计卡片 */}
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={6}>
            <Card loading={loading}>
              <Statistic title='总用户数' value={userStats?.total ?? "--"} prefix={<UserOutlined />} valueStyle={{ color: "#3f8600" }} />
            </Card>
          </Col>
          <Col span={6}>
            <Card loading={loading}>
              <Statistic title='文章总数' value={articleStats?.total ?? "--"} prefix={<FileTextOutlined />} valueStyle={{ color: "#1890ff" }} />
            </Card>
          </Col>
          <Col span={6}>
            <Card loading={loading}>
              <Statistic title='产品总数' value={productStats?.total ?? "--"} prefix={<ShoppingOutlined />} valueStyle={{ color: "#722ed1" }} />
            </Card>
          </Col>
          <Col span={6}>
            <Card loading={loading}>
              <Statistic title='攻略总数' value={caseStats?.total ?? "--"} prefix={<FileTextOutlined />} valueStyle={{ color: "#eb2f96" }} />
            </Card>
          </Col>
        </Row>

        {/* 最近文章 */}
        <Card title='最近文章' style={{ marginBottom: 24 }}>
          <Table columns={articleColumns} dataSource={recentArticles} rowKey='id' loading={loading} pagination={false} size='small' />
        </Card>

        {/* 最近攻略 */}
        <Card title='最近攻略' style={{ marginBottom: 24 }}>
          <Table columns={caseColumns} dataSource={recentCases} rowKey='id' loading={loading} pagination={false} size='small' />
        </Card>

        {/* 最近产品 */}
        <Card title='最近产品'>
          <Table columns={productColumns} dataSource={recentProducts} rowKey='id' loading={loading} pagination={false} size='small' />
        </Card>
      </div>
    </AdminLayout>
  );
}
